package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 增加用户
func AddUser(c *gin.Context) {
	var userData model.User
	if err := c.BindWith(&userData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	userData.CreateTime = local
	userData.UpdateTime = local
	userData.Salt = ""
	userData.Avatar = ""
	insertId, err := userData.AddUser()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("添加失败"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("创建成功", m))
}

func GetUserList(c *gin.Context) {
	// 获取参数
	pageSize, _ := util.StringToInt64(c.DefaultQuery("pageSize", "10"))
	pageIndex, _ := util.StringToInt64(c.DefaultQuery("pageIndex", "1"))
	deptId, _ := util.StringToInt64(c.DefaultQuery("deptId", "0"))
	var userData model.User
	m, err := userData.GetUserList(pageIndex, pageSize, deptId)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("查询失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 更新用户
func UpdateUser(c *gin.Context) {
	var userData model.User
	if err := c.BindWith(&userData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	if err := userData.UpdateUser(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("更新失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", nil))
}

// 删除用户
func DeleteUser(c *gin.Context) {
	var userData model.User
	userId, _ := util.StringToInt64(c.Param("userId"))
	if err := userData.DeleteUser(userId); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", nil))
}

// 用户账号密码登录
func LoginByUserNameAndPassWord(c *gin.Context) {
	var userData model.User
	username := c.DefaultQuery("username", "")
	password := c.DefaultQuery("password", "")
	userData.Username = username
	userData.Password = password
	token, err := userData.LoginByUserNameAndPassWord()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("账号或密码错误"))
		return
	}
	m := make(map[string]interface{})
	m["token"] = token
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 获取用户详细信息
func GetInfo(c *gin.Context) {
	// 获取token
	token := c.GetHeader("Authorization")
	token = string([]rune(token)[7:len(token)])
	// 解析token
	myClaims, err := util.ParseToken(token)
	if err != nil {
		return
	}
	user, err := model.GetUserByUsername(myClaims.Username)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取用户信息失败"))
		return
	}
	m := make(map[string]interface{})
	m["data"] = user
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}


